package com.ebring.shareEducation.controller;

import com.ebring.shareEducation.bean.CompanyPay;
import com.ebring.shareEducation.bean.Taskrelease;
import com.ebring.shareEducation.bean.User;
import com.ebring.shareEducation.service.CompanyPayService;
import com.ebring.shareEducation.service.UserService;
import com.ebring.shareEducation.util.CertHttpUtil;
import com.ebring.shareEducation.util.MD5Util;
import com.ebring.shareEducation.util.XMLUtil;
import com.ebring.shareEducation.utils.RspMsg;
import com.ebring.shareEducation.utils.UuidUtils;
import com.ebring.shareEducation.utils.WeChat.TranspositionCoin;
import org.jdom.JDOMException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.*;

@RestController
public class CompanyPayController {
    private static final Logger LOGGER = LoggerFactory.getLogger(CompanyPayController.class);
    private String mch_appid = "wx4d47c22d8343e4c8";
    private String mchid = "1361219402";
    private String check_name = "NO_CHECK";
    private String spbill_create_ip = "1.85.0.98";
    private String partnerkey = "ebringweixinpay1ebringweixinpay2";
    private String companyUrl = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
    private String certPath = "D:\\EbringCode\\cert\\1361219402_20181123_cert.p12";
    @Autowired
    private UserService userService;
    @Autowired
    private CompanyPayService companyPayService;

    @PostMapping("/wechat/companyPay/payToEmployer")
    public RspMsg payToEmployer(Taskrelease task, User user) {
        RspMsg rspMsg = new RspMsg();
        if (task == null) {
            rspMsg.setError();
            rspMsg.setMsg("找不到该任务");
            LOGGER.info("in CompanyPayController payToEmployer , task is not exists!");
            return rspMsg;
        }
        String taskId = task.getTaskReleaseId();
        if (user == null) {
            rspMsg.setError();
            rspMsg.setMsg("in CompanyPayController payToEmployer , user  is not exists!");
            return rspMsg;
        }
        String openid = user.getOpenid();
        String amount = TranspositionCoin.changeY2F(task.getTaskPrice());
        String desc = task.getTaskReleaseName();
        //随即字符串
        String partner_trade_no = UuidUtils.getNumberId(20);
        String nonce_str = UUID.randomUUID().toString().replaceAll("-", "");
        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        packageParams.put("mch_appid", mch_appid);
        packageParams.put("mchid", mchid);
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("partner_trade_no", partner_trade_no);
        packageParams.put("openid", openid);
        packageParams.put("check_name", check_name);
        packageParams.put("amount", amount);
        packageParams.put("desc", desc);
        packageParams.put("spbill_create_ip", spbill_create_ip);

        String sign = createSign(packageParams, partnerkey);
        LOGGER.info("in CompanyPayController payToEmployer , WeChat sign : " + sign);

        String xml = "<xml>" +
                "<mch_appid>" + mch_appid + "</mch_appid>" +
                "<mchid>" + mchid + "</mchid>" +
                "<nonce_str>" + nonce_str + "</nonce_str>" +
                "<partner_trade_no>" + partner_trade_no + "</partner_trade_no>" +
                "<openid>" + openid + "</openid>" +
                "<check_name>" + check_name + "</check_name>" +
                "<amount>" + amount + "</amount>" +
                "<desc>" + desc + "</desc>" +
                "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>" +
                "<sign>" + sign + "</sign>" +
                "</xml>";
        LOGGER.info("in CompanyPayController payToEmployer,xml:" + xml);
        String result = CertHttpUtil.postData(mchid, companyUrl, xml, certPath);
        LOGGER.info("in CompanyPayController payToEmployer,result:" + result);
        CompanyPay companyPay = new CompanyPay();
        try {
            Map map = XMLUtil.doXMLParse(result);

            String return_msg = (String) map.get("return_msg");
            String return_code = (String) map.get("return_code");
            String result_code = "";
            if ("SUCCESS".equals(return_code)) {
                result_code = (String) map.get("result_code");
                if ("SUCCESS".equals(result_code)) {
                    String payment_no = (String) map.get("payment_no");
                    String payment_time = (String) map.get("payment_time");
                    companyPay.setWechatPaymentNo(payment_no);
                    companyPay.setPaymentTime(payment_time);
                } else {
                    String err_code = (String) map.get("err_code");
                    String err_code_des = (String) map.get("err_code_des");
                    companyPay.setErrCode(err_code);
                    companyPay.setErrCodeDes(err_code_des);
                }

            } else {

            }
            companyPay.setPaymentId(UuidUtils.getUUID());
            companyPay.setPartnerTradeNo(partner_trade_no);
            companyPay.setReturnCode(return_code);
            companyPay.setReturnMsg(return_msg);
            companyPay.setResultCode(result_code);
            companyPay.setOrderNo(taskId);
            companyPay.setAmount(amount);
            companyPay.setOpenid(openid);
            companyPay.setDescribe(desc);
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        rspMsg.setOK();
        rspMsg.setResult(companyPay);
        return rspMsg;
    }

    /**
     * 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
     */
    public String createSign(SortedMap<String, String> packageParams, String partnerkey) {
        StringBuffer sb = new StringBuffer();
        Set es = packageParams.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if (null != v && !"".equals(v) && !"sign".equals(k)
                    && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + partnerkey);
        System.out.println("md5 sb:" + sb);
        String sign = MD5Util.MD5Encode(sb.toString(), "UTF-8")
                .toUpperCase();
        return sign;
    }

    /**
     * 金币提现
     *
     * @param userId  用户id
     * @param money   提现金额 单位元
     * @param orderId 金币流水单id
     * @return
     */
    @PostMapping("/wechat/companyPay/coinCash")
    public RspMsg<CompanyPay> coinCash(String userId, String money, String orderId) {
        RspMsg<CompanyPay> rspMsg = new RspMsg();
        User user = userService.selectUserBeanByUserId(userId);
        String openid = user.getOpenid();
        String amount = TranspositionCoin.changeY2F(money);
        String desc = "金币提现";
        //随即字符串
        String partner_trade_no = UuidUtils.getNumberId(20);
        String nonce_str = UUID.randomUUID().toString().replaceAll("-", "");
        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        packageParams.put("mch_appid", mch_appid);
        packageParams.put("mchid", mchid);
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("partner_trade_no", partner_trade_no);
        packageParams.put("openid", openid);
        packageParams.put("check_name", check_name);
        packageParams.put("amount", amount);
        packageParams.put("desc", desc);
        packageParams.put("spbill_create_ip", spbill_create_ip);

        String sign = createSign(packageParams, partnerkey);
        LOGGER.info("in CompanyPayController coinCash , WeChat sign : " + sign);

        String xml = "<xml>" +
                "<mch_appid>" + mch_appid + "</mch_appid>" +
                "<mchid>" + mchid + "</mchid>" +
                "<nonce_str>" + nonce_str + "</nonce_str>" +
                "<partner_trade_no>" + partner_trade_no + "</partner_trade_no>" +
                "<openid>" + openid + "</openid>" +
                "<check_name>" + check_name + "</check_name>" +
                "<amount>" + amount + "</amount>" +
                "<desc>" + desc + "</desc>" +
                "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>" +
                "<sign>" + sign + "</sign>" +
                "</xml>";
        LOGGER.info("in CompanyPayController coinCash , xml:" + xml);
        String result = CertHttpUtil.postData(mchid, companyUrl, xml, certPath);
        LOGGER.info("in CompanyPayController coinCash , result:" + result);
        CompanyPay companyPay = new CompanyPay();
        try {
            Map map = XMLUtil.doXMLParse(result);

            String return_msg = (String) map.get("return_msg");
            String return_code = (String) map.get("return_code");
            String result_code = "";


            if ("SUCCESS".equals(return_code)) {
                result_code = (String) map.get("result_code");
                if ("SUCCESS".equals(result_code)) {
                    String payment_no = (String) map.get("payment_no");
                    String payment_time = (String) map.get("payment_time");
                    companyPay.setWechatPaymentNo(payment_no);
                    companyPay.setPaymentTime(payment_time);
                    rspMsg.setOK();
                } else {
                    String err_code = (String) map.get("err_code");
                    String err_code_des = (String) map.get("err_code_des");
                    companyPay.setErrCode(err_code);
                    companyPay.setErrCodeDes(err_code_des);
                    rspMsg.setError();
                    rspMsg.setMsg(err_code_des);
                }
            } else {
                rspMsg.setError();
                rspMsg.setMsg(return_msg);
                return rspMsg;
            }
            companyPay.setUserId(userId);
            companyPay.setPaymentId(UuidUtils.getUUID());
            companyPay.setPartnerTradeNo(partner_trade_no);
            companyPay.setReturnCode(return_code);
            companyPay.setReturnMsg(return_msg);
            companyPay.setResultCode(result_code);
            companyPay.setOrderNo(orderId);
            companyPay.setAmount(amount);
            companyPay.setOpenid(openid);
            companyPay.setDescribe(desc);
            RspMsg<CompanyPay> companyPayRspMsg = companyPayService.insertCompanyPayBill(companyPay);
            LOGGER.info("in CompanyPayController coinCash , insertCompanyPayBill result : " + companyPayRspMsg.getCode());
            if (-1 == companyPayRspMsg.getCode()) {
                rspMsg.setError();
                rspMsg.setMsg("数据库操作失败!");
            }
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        rspMsg.setResult(companyPay);
        return rspMsg;
    }
}
